﻿using FreeDream.Common;
using log4net;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace FreeDream.Infrastructure
{
    public static class SwaggerSetup
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(SwaggerSetup));
        /// <summary>
        /// Swagger 启动服务
        /// </summary>
        /// <param name="services"></param>
        public static void AddSwaggerSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            var basePath = AppContext.BaseDirectory;

            services.AddSwaggerGen(c =>
            {
                //var version = "v1";
                //var ApiName = "后台管理平台";
                //c.SwaggerDoc(version, new OpenApiInfo
                //{
                //    Version = version,
                //    Title = $"{ApiName} 接口文档——{RuntimeInformation.FrameworkDescription}",
                //    Description = $"{ApiName} HTTP API " + version,
                //    //Contact = new OpenApiContact { Name = ApiName, Email = "Blog.Core@xxx.com", Url = new Uri("https://neters.club") },
                //    //License = new OpenApiLicense { Name = ApiName + " 官方文档", Url = new Uri("http://apk.neters.club/.doc/") }
                //});

                var ApiName = "后台管理平台";
                //遍历出全部的版本，做文档信息展示
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{ApiName} 接口文档——{RuntimeInformation.FrameworkDescription}",
                        Description = $"{ApiName} HTTP API " + version,
                        //Contact = new OpenApiContact { Name = ApiName, Email = "Blog.Core@xxx.com", Url = new Uri("https://neters.club") },
                        //License = new OpenApiLicense { Name = ApiName + " 官方文档", Url = new Uri("http://apk.neters.club/.doc/") }
                    });
                    c.OrderActionsBy(o => o.RelativePath);
                });

                try
                {
                    //这个就是刚刚配置的xml文件名
                    var xmlPath = Path.Combine(basePath, "FreeDream.WebApi.xml");//Blog.Core.xml
                                                                                          //默认的第二个参数是false，这个是controller的注释，记得修改
                    c.IncludeXmlComments(xmlPath, true);

                    ////这个就是Model层的xml文件名
                    //var xmlModelPath = Path.Combine(basePath, "Blog.Core.Model.xml");
                    //c.IncludeXmlComments(xmlModelPath);
                }
                catch (Exception ex)
                {
                    log.Error("swagger文档加载失败,xml丢失，请检查并拷贝。\n" + ex.Message);
                    Console.WriteLine("swagger 文档加载失败" + ex.Message);
                }

                #region Swashbuckle.AspNetCore.Filters

                ////参考文章：http://www.zyiz.net/tech/detail-134965.html
                ////需要安装包Swashbuckle.AspNetCore.Filters
                //// 开启权限小锁 需要在对应的Action上添加[Authorize]才能看到
                //c.OperationFilter<AddResponseHeadersFilter>();
                //c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                ////在header 中添加token，传递到后台
                //c.OperationFilter<SecurityRequirementsOperationFilter>();

                #endregion

                // ids4和jwt切换   Permissions.IsUseIds4
                if (false)
                {
                    //接入identityserver4
                    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                    {
                        Type = SecuritySchemeType.OAuth2,
                        Flows = new OpenApiOAuthFlows
                        {
                            Implicit = new OpenApiOAuthFlow
                            {
                                AuthorizationUrl = new Uri($"{AppSettings.App(new string[] { "Startup", "IdentityServer4", "AuthorizationUrl" })}/connect/authorize"),
                                Scopes = new Dictionary<string, string>
                                {
                                    {
                                        "core.api","ApiResource id"
                                    }
                                }
                            }
                        }
                    });
                }
                else
                {
                    c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme,
                    new OpenApiSecurityScheme
                    {
                        In = ParameterLocation.Header,
                        Description = "请输入Login接口返回的Token，前置Bearer。示例：Bearer {Token}",
                        Name = "Authorization",//jwt默认的参数名称,
                        Type = SecuritySchemeType.ApiKey, //指定ApiKey
                        BearerFormat = "JWT",//标识承载令牌的格式 该信息主要是出于文档目的
                        Scheme = JwtBearerDefaults.AuthenticationScheme//授权中要使用的HTTP授权方案的名称
                    });
                }

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                            //,Scheme = "oauth2",Name = "Bearer",In = ParameterLocation.Header,
                        },
                        new List<string>()
                    }
                });
            });

            //services.AddSwaggerGenNewtonsoftSupport();
        }


        //public static void UseSwagger(this IApplicationBuilder app)
        //{
        //    app.UseSwagger(c =>
        //    {
        //        c.RouteTemplate = "swagger/{documentName}/swagger.json";
        //        c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
        //        {
        //            var url = $"{httpReq.Scheme}://{httpReq.Host.Value}";
        //            var referer = httpReq.Headers["Referer"].ToString();
        //            //if (referer.Contains(GlobalConstant.DevApiProxy))
        //            //    url = referer.Substring(0,
        //            //        referer.IndexOf(GlobalConstant.DevApiProxy, StringComparison.InvariantCulture) + GlobalConstant.DevApiProxy.Length - 1);
        //            swaggerDoc.Servers =
        //                new List<OpenApiServer>
        //                {
        //                    new OpenApiServer
        //                    {
        //                        Url = url
        //                    }
        //                };
        //        });
        //    });
        //    app.UseSwaggerUI(c => c.SwaggerEndpoint("v1/swagger.json", "ZrAdmin v1"));
        //}



    }

    /// <summary>
    /// Api接口版本 自定义
    /// </summary>
    public enum ApiVersions
    {
        /// <summary>
        /// V1 版本
        /// </summary>
        V1 = 1,
        /// <summary>
        /// V2 版本
        /// </summary>
        V2 = 2,
    }
}
